package dawnland03.data.map.model;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * User: Petru Obreja (obrejap@yahoo.com)
 * Date: Jun 2, 2010
 * Time: 8:44:02 PM
 */
public class EntityMatrixCellLayer {
    private final Integer matrixCellId;
    private Integer entityId;
    private final Semaphore cellSemaphore;

    public EntityMatrixCellLayer(Integer matrixCellId) {
        this.matrixCellId = matrixCellId;
        cellSemaphore = new Semaphore(1, true); //fair - true if this semaphore will guarantee first-in first-out granting of permits under contention, else false.
    }

    public boolean tryAcquire(Integer entityId, long timeout) {
        if(this.entityId == entityId){
            return true; //already acquired
        }
        try {
            boolean acquired = cellSemaphore.tryAcquire(timeout, TimeUnit.SECONDS);
            if (acquired) {
                this.entityId = entityId;
            }
            return acquired;
        } catch (InterruptedException e) {
            e.printStackTrace();
            return false;
        }
    }

    public void releaseLockOnEntityLayer(Integer entityId) {
        if (this.entityId == entityId) {
            synchronized (this) {
                cellSemaphore.release();
                this.entityId = null;
            }
        }
    }
}
